package com.example.listener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.dto.UserDto;
import com.example.entity.Account1;
import com.example.event.AddIntegralEvent;
import com.example.mapper.Account1Mapper;
import com.example.service.Account1Service;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

/**
 * Created by IntelliJ IDEA2021.3
 * @Author: Tenghw
 * @Date: 2022/09/26  20:17
 * @Description: 事件监听器类Account1Listener
 */
@Slf4j
@Component //注册该事件监听器
public class Account1Listener implements ApplicationListener<AddIntegralEvent> {

    @Autowired
    Account1Mapper account1Mapper;
    @Autowired
    Account1Service account1Service;

    @Async(value = "asyncThreadPoolTaskExecutor")//使用该指定的自定义线程池
    //@Async(value = "async-executor-guava")
    @SneakyThrows
    @Override
    public void onApplicationEvent(AddIntegralEvent event) {
        Object source = event.getSource();
        UserDto userDto = (UserDto) source;
        //当前时间(毫秒)
        //long now = DateUtil.current();
        LocalDateTime now = LocalDateTime.now();
        log.warn("@Async标注的方法 ===> 当前时间：{}，event.getSource:{}", now, userDto);
        //比如业务时增加积分的，把注册成功后account1的积分字段，从0更为500
        //boolean b = account1Mapper.updateIntegralById(userDto);
        //if (!b) {
        //    throw new RuntimeException("增加积分失败...");
        //}
        log.warn("@Async标注的方法 ===> 当前时间：{} ===> 异步调用成功，该新增账户赠送500积分成功！", now);
        account1Service.update(Wrappers.<Account1>update().lambda().set(Account1::getIntegral, userDto.getIntegral()).eq(Account1::getId, userDto.getUserId()));
    }
}
